#include "StdAfx.h"
#include "TriggerListener.h"

namespace _MODULE_
{
	namespace _GAME_
	{
		std::multimap<_FO_UTIL::Name,TriggerListener*> TriggerListener::s_mmapTriggerListener;

		TriggerListener::TriggerListener(void)
		{
			m_nameTag=_FOGGE_::Name_None;
		}

		TriggerListener::~TriggerListener(void)
		{
		}

		void TriggerListener::SetName(_FO_UTIL::Name& name)
		{
			if(m_nameTag==name)
				return;

			RemoveFromTriggerMap();

			m_nameTag = name;

			InsertToTriggerMap();
		}
		void TriggerListener::SetName(_FOGGE_::foString& name)
		{
			_FO_UTIL::Name newName(name);
			SetName(newName);
		}
			

		void TriggerListener::SetName(LPCTSTR name)
		{
			_FO_UTIL::Name newName(name);
			SetName(newName);
		}


		void TriggerListener::RemoveFromTriggerMap()
		{
			if(m_nameTag==_FOGGE_::Name_None)
				return;

			std::multimap<_FO_UTIL::Name,TriggerListener*>::iterator iterTL;

			iterTL = s_mmapTriggerListener.find(m_nameTag);

			if(iterTL != s_mmapTriggerListener.end())
			{//found
				//find exact location
				while(iterTL->second!=this)
					++iterTL;
				//remove from map
				s_mmapTriggerListener.erase(iterTL);
			}
		}

		void TriggerListener::InsertToTriggerMap()
		{
			if(m_nameTag==_FOGGE_::Name_None)
				return;

			typedef std::multimap<_FO_UTIL::Name,TriggerListener*>::value_type TriggerListeneValueType;
			s_mmapTriggerListener.insert(TriggerListeneValueType(m_nameTag,this));

		}

		void TriggerListener::TriggerEvent(_FO_UTIL::Name name,_P_GAME::GamePart* Instigator)
		{
			std::multimap<_FO_UTIL::Name,TriggerListener*>::const_iterator iterTL;

			iterTL = s_mmapTriggerListener.find(name);

			if(iterTL != s_mmapTriggerListener.end())
			{//found

				//signal to all triggers that have a same name.
				
				do
				{
					iterTL->second->Trigger(Instigator);
				}
				while((++iterTL)->first==name);
				
			}
		}
	}
}